// src/utils/AudioPlayer.js
class AudioPlayer {
  constructor() {
    this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
    this.audioBuffer = null;
    this.addAudioDatas = [];
  }

  async loadAudioData(base64String) {
    const response = await fetch(`data:audio/x-wav;base64,${base64String}`);
    const arrayBuffer = await response.arrayBuffer();
    this.audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer);
  }

  play() {
    if (this.audioBuffer) {
      const source = this.audioContext.createBufferSource();
      source.buffer = this.audioBuffer;
      source.connect(this.audioContext.destination);
      source.start(0);
    }
  }

  addAudioData(base64String) {
    this.addAudioDatas.push(base64String);
  }

  playAll() {
    if (this.addAudioDatas.length > 0) {
      this.loadAudioData(this.addAudioDatas[0]).then(() => {
        this.play();
        this.addAudioDatas.shift();
        if (this.addAudioDatas.length > 0) {
          setTimeout(() => this.playAll(), 1000); // 延迟播放下一个音频
        }
      });
    }
  }
}

export default AudioPlayer;